package code.cando;

/**
 * author : yeswater
 * date : 2023/12/4
 */

public class T002 {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(2);
        l1.next = new ListNode(4, new ListNode(3));
        ListNode l2 = new ListNode(5);
        l2.next = new ListNode(6, new ListNode(4));
        ListNode node = addTwoNumbers2(l1, l2);
        while (node != null) {
            System.out.print(node.val + "=>");
            node = node.next;
        }
    }

    /**
     * 上下两种解法思路差不多 下面用三元运算符 代码简洁一点
     */
    
    // 自己的除暴解法
    public static ListNode addTwoNumbers1(ListNode l1, ListNode l2) {
        ListNode l3 = new ListNode();
        ListNode l4 = l3;
        int flag = 0; //进位
        while (l1 != null || l2 != null) {
            
            if (l1 != null && l2 != null) {
                l4.next = new ListNode(l1.val + l2.val + flag);
                flag = l4.next.val / 10;
                l4.next.val = l4.next.val % 10;
            }

            if (l1 != null && l2 == null) {
                l4.next = new ListNode(l1.val + flag);
                flag = l4.next.val / 10;
                l4.next.val = l4.next.val % 10;
            }

            if (l1 == null && l2 != null) {
                l4.next = new ListNode(l2.val + flag);
                flag = l4.next.val / 10;
                l4.next.val = l4.next.val % 10;
            }
            l4 = l4.next;
            l1 = l1 == null ? null : l1.next;
            l2 = l2 == null ? null : l2.next;
        }
        if (flag == 1) {
            l4.next = new ListNode(1);
        }
        // return pre.next;
        return l3.next;
    }

    // 题解里面学的优雅解法
    public static ListNode addTwoNumbers2(ListNode l1, ListNode l2) {
        ListNode pre = new ListNode();
        ListNode cur = pre;
        int flag = 0; // 进位
        while(l1 != null || l2 != null) {
            int x = l1 == null ? 0 : l1.val;
            int y = l2 == null ? 0 : l2.val;
            int sum = x + y + flag;
            flag = sum / 10;
            sum = sum % 10;
            cur.next = new ListNode(sum);
            cur = cur.next;
            
            l1 = l1 == null ? null : l1.next;
            l2 = l2 == null ? null : l2.next;
        }
        return pre.next;
    }
    

    private static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
